package com.sanniu.common;

import com.sanniu.model.common.PublicAction;
import io.jboot.Jboot;

import java.util.ArrayList;
import java.util.List;

public class PermissionManager {
    private static final PermissionManager me = new PermissionManager();

    private static List<PublicAction> publicActionlist = new ArrayList<PublicAction>();

    public PermissionManager() {

    }

    public static PermissionManager me() {
        return me;
    }

    public void init() {
        String publicConfig = Jboot.configValue("permission.public");
        System.out.println("permission.public:" + publicConfig);
        String[] publicConfigArray = publicConfig.split(";");
        //System.out.println(publicConfigArray.length);
        for (int i = 0; i < publicConfigArray.length; i++) {
            String[] tempArray = publicConfigArray[i].split(":");
            PublicAction publicAction = new PublicAction();
            publicAction.setControllerName(tempArray[0]);
            //System.out.println(tempArray);
            if (tempArray[1].equals("*")) {
                publicAction.setAllController(true);
            } else {
                publicAction.setAllController(false);
                String[] tempArray2 = tempArray[1].split(",");
                List<String> ignoreAction = new ArrayList<String>();
                for (int j = 0; j < tempArray2.length; j++) {
                    ignoreAction.add(tempArray2[j]);
                }
                publicAction.setActionNameList(ignoreAction);
            }
            publicActionlist.add(publicAction);
        }
        System.out.println(publicActionlist.size());
        System.out.println(publicActionlist);
    }

    /**
     * 检查是否需要检测token
     *
     * @param controllerName
     * @param actionName
     * @return
     */
    public static Boolean checkRequireToken(String controllerName, String actionName) {
        //System.out.println(publicActionlist);
        //System.out.println(controllerName);
        //System.out.println(actionName);
        Boolean requireToken = true;
        for (PublicAction item : publicActionlist) {
            //System.out.println(item.getControllerName() + "_" + controllerName);
            if (item.getControllerName().equals(controllerName)) {
                if (item.getAllController() || item.getActionNameList().contains(actionName)) {
                    requireToken = false;
                    break;
                }
            }
        }
        System.out.println(requireToken);
        return requireToken;
    }

}
